<?php

/**
 * @author Immanuel Bauer | 0626117
 */
class TodoList {
	
	/**
	 *  @var int 
	 */
	private $id;
	
	/**
	 *  @var string 
	 */
	private $name;
	
	/**
	 *  @var string
	 */
	private $description;
	
	/**
	 *  @var int 
	 */
	private $ownerID;
	
	/**
	 *  @var timestamp 
	 */
	private $creationDate;
	
	/**
	 * Creates an instance of the TodoList model with the given data
	 * @param string $name
	 * @param string $description
	 * @param int $ownerID
	 */
	function __construct($name, $description, $ownerID) {
		$this->id = null;
		$this->name = $name;
		$this->description = $description;
		$this->creationDate = time();
		$this->ownerID = (int)$ownerID;
	}
	
	/**
	 * Fetches the todo list data for the given id and returns a TodoList object with the data.
	 * Returns null if the todo list doesn't exist.
	 * 
	 * @param int $id
	 * @return TodoList
	 */
	public static function getList($id){
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'lists WHERE id = \''.mysql_real_escape_string($id).'\';');
		$row = mysql_fetch_assoc($qry);
		if(isset($row['id'])){
			$list = new TodoList($row['name'], $row['description'], $row['owner']);	
			$list->setID($row['id']);
			$list->setCreationDate($row['creation_date']);
			return $list;
		} else {
			return null;
		}
	}
	
	/**
	 * Fetches the Lists mathing the given parameters
	 * 
	 * @param int $userID
	 * @param boolean $public
	 * @param int $from
	 * @param int $rows
	 * @param string $sort "t" or "cD"
	 * @param string $order "asc" or "desc"
	 * @param boolean $includingPast
	 * 
	 * @return array<TodoList> 
	 */
	public static function getLists($userID = -1, $public = false, $from = 0, $rows = 30, $sort = 't', $order = 'asc', $owner = false){
		
		if(!$owner) $where = '(l.owner = \''.mysql_real_escape_string($userID).'\' OR slu.user = \''.mysql_real_escape_string($userID).'\') ';
		else $where = 'l.owner = \''.mysql_real_escape_string($userID).'\' ';
		
		if($public){
			if(!$owner) $where .= 'OR slu.user = \'-1\'';
		} else {
			$where .= 'AND (slu.user != \'-1\' OR slu.user IS NULL)';
		}
		
		switch($sort){
			case 't': $sort = 'l.name'; break;
			case 'cD': $sort = 'l.creation_date'; break;
			default: $sort = 'l.name'; break;
		}
		
		switch($order){
			case 'desc': $order = 'DESC'; break;
			case 'd': $order = 'DESC'; break;
			case 'asc': $order = 'ASC'; break;
			case 'a': $order = 'ASC'; break;
			default: $order = 'ASC'; break;
		}
		
		$limit = '';
		if($rows >= 0){
			$limit = 'LIMIT '.mysql_real_escape_string($from).', '.mysql_real_escape_string($rows);
		}
		
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'lists AS l LEFT JOIN '.TABLE_PREFIX.'share_list_user AS slu ON slu.list = l.id WHERE '.$where.' GROUP BY l.id ORDER BY '.$sort.' '.$order.' '.$limit.' ;');
		
		$a = array();
		while($row = mysql_fetch_assoc($qry)){
			$list = new TodoList($row['name'], $row['description'], $row['owner']);	
			$list->setID($row['id']);
			$list->setCreationDate($row['creation_date']);
			array_push($a, $list);
		}
		
		return $a;
	}
	
	/**
	 * Fetches the Lists linked with the given Todo
	 * 
	 * @param int $todoID
	 * 
	 * @return array<TodoList> 
	 */
	public static function getListsLinkedWithTodo($todoID){
		
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'lists AS l LEFT JOIN '.TABLE_PREFIX.'todo_list AS tl ON tl.list = l.id WHERE tl.todo = \''.mysql_real_escape_string($todoID).'\' GROUP BY l.id;');
		
		$a = array();
		while($row = mysql_fetch_assoc($qry)){
			$list = new TodoList($row['name'], $row['description'], $row['owner']);	
			$list->setID($row['id']);
			$list->setCreationDate($row['creation_date']);
			array_push($a, $list);
		}
		
		return $a;
	}
	
	/**
	 * Fetches the number of Lists matching th egiven parameters
	 * 
	 * @param int $userID
	 * @param boolean $public
	 * @param boollean $includingPast
	 * 
	 * @return int count of lists
	 */
	public static function getListCount($userID = -1, $public = false, $owner = false){
		
		if(!$owner) $where = '(l.owner = \''.mysql_real_escape_string($userID).'\' OR slu.user = \''.mysql_real_escape_string($userID).'\') ';
		else $where = 'l.owner = \''.mysql_real_escape_string($userID).'\' ';
		
		if($public){
			if(!$owner) $where .= 'OR slu.user = \'-1\'';
		} else {
			$where .= 'AND (slu.user != \'-1\' OR slu.user IS NULL)';
		}
		
		$qry = mysql_query('SELECT count(DISTINCT l.id) FROM '.TABLE_PREFIX.'lists AS l LEFT JOIN '.TABLE_PREFIX.'share_list_user AS slu ON slu.list = l.id WHERE '.$where.';');
		
		$res = mysql_fetch_row($qry);
		
		return (int)$res[0];
	}
	
	/**
	 * Shares a list with a user and returns true if succesfull otherwise false.
	 * If the given userID is -1 or omitted the list will be shared with all users.
	 * 
	 * @param int $listID
	 * @param int $userID
	 * 
	 * @return boolean
	 */
	public static function shareTodoListWithUser($listID, $userID = -1){
		//check if already shared
		$share = mysql_fetch_assoc(mysql_query('SELECT * FROM '.TABLE_PREFIX.'share_list_user WHERE list = \''.mysql_real_escape_string($listID).'\' AND user = \''.mysql_real_escape_string($userID).'\';'));
		
		if(!isset($share['list'])){
			//check if user and list exist
			if($userID != -1) $user = User::getUser($userID);
			else $user = true;
			$list = TodoList::getList($listID);
			if(!is_null($user) && !is_null($list)){
				return mysql_query('INSERT INTO '.TABLE_PREFIX.'share_list_user (`list`,`user`) VALUES (\''.mysql_real_escape_string($listID).'\', \''.mysql_real_escape_string($userID).'\');');
			} else return false;
		} else return true;
	}
	
	/**
	 * Unshares a list with a user and returns true if succesfull otherwise false. 
	 * If the given userID is -1 or omitted all shares of the list will be removed.
	 * 
	 * @param int $listID
	 * @param int $userID If -1 all links from the given list will be broken.
	 * 
	 * @return boolean
	 */
	public static function unshareTodoListWithUser($listID, $userID = -1){
		//check if shared
		$share = mysql_fetch_assoc(mysql_query('SELECT * FROM '.TABLE_PREFIX.'share_list_user WHERE list = \''.mysql_real_escape_string($listID).'\' AND user = \''.mysql_real_escape_string($userID).'\';'));
		
		if($userID == -1){
			return mysql_query('DELETE FROM '.TABLE_PREFIX.'share_list_user WHERE list = \''.mysql_real_escape_string($listID).'\';');
		} else if(isset($share['list'])){
			return mysql_query('DELETE FROM '.TABLE_PREFIX.'share_list_user WHERE list = \''.mysql_real_escape_string($listID).'\' AND user = \''.mysql_real_escape_string($userID).'\';');
		} else return false;
	}
	
	/**
	 * Saves the current state of the model object into the database
	 * @return boolean true if save was successfull
	 */
	public function saveToDB(){
		if(is_null($this->id)){
			//insert
			$qry = mysql_query('INSERT INTO '.TABLE_PREFIX.'lists (`id`, `name`, `description`, `owner`, `creation_date`) VALUES (
				\'\',
				\''.mysql_real_escape_string($this->name).'\',
				\''.mysql_real_escape_string($this->description).'\',
				\''.mysql_real_escape_string($this->ownerID).'\',
				\''.mysql_real_escape_string($this->creationDate).'\'
			);');
			if($qry){
				$qry = mysql_query('SELECT id FROM '.TABLE_PREFIX.'lists
					 WHERE `name` = \''.mysql_real_escape_string($this->name).'\'
					 	AND `description` = \''.mysql_real_escape_string($this->description).'\' 
					 	AND `owner` = \''.mysql_real_escape_string($this->ownerID).'\'
					 	AND `creation_date` = \''.mysql_real_escape_string($this->creationDate).'\'
				;');
				$row = mysql_fetch_assoc($qry);
				if(isset($row['id'])){
					$this->id = (int)$row['id'];
					return true;
				} else{
					return false;
				}
			} else {
				return false;
			}
		} else {
			//update
			$qry = mysql_query('UPDATE '.TABLE_PREFIX.'lists SET 
				`name` = \''.mysql_real_escape_string($this->name).'\',
				`description` = \''.mysql_real_escape_string($this->description).'\',
				`owner` = \''.mysql_real_escape_string($this->ownerID).'\'
			WHERE id = \''.mysql_real_escape_string($this->id).'\';');
			return $qry;
		}
	}
	
	/**
	 * Removes the model object's corresponding row in the database and returns true if successfull.
	 * @return boolean
	 */
	public function removeFromDB(){
		if(!is_null($this->id)){
			return mysql_query('DELETE FROM '.TABLE_PREFIX.'lists WHERE id = \''.mysql_real_escape_string($this->id).'\';');
		} else {
			return true;
		}
	}
	
	/**
	 * Returns true if this list is public otherwise false
	 * @return boolean
	 */
	public function isPublic(){
		$qry = mysql_fetch_assoc(mysql_query('SELECT list FROM '.TABLE_PREFIX.'share_list_user WHERE list = \''.mysql_real_escape_string($this->id).'\' AND user = \'-1\';'));
		return isset($qry['list']);
	}
	
/* ####### GETTER ####### */
	
	/**
	 * The List's id.
	 * @return int
	 */
	public function getID(){
		return $this->id;
	}
	
	/**
	 * The List's name.
	 * @return string
	 */
	public function getName(){
		return $this->name;
	}
	
	/**
	 * The List's description.
	 * @return string
	 */
	public function getDescription(){
		return $this->description;
	}

	/**
	 * The List's Owner id.
	 * @return int
	 */
	public function getOwnerID(){
		return $this->ownerID;
	}
	
	/**
	 * The List's creation date.
	 * @return timestamp
	 */
	public function getCreationDate(){
		return $this->creationDate;
	}
	
/* ####### SETTER ####### */
	
	/**
	 * Sets the List's id.
	 * @param int $id
	 */
	private function setID($id){
		$this->id = (int)$id;
	}
	
	/**
	 * Sets the List's name.
	 * @param string $name
	 */
	public function setName($name){
		$this->name = $name;
	}
	
	/**
	 * Sets the List's description.
	 * @param string $description
	 */
	public function setDescription($description){
		$this->description = $description;
	}

	/**
	 * Sets the List's owner id.
	 * @parem int $id
	 */
	public function setOwnerID($id){
		$this->ownerID = (int)$id;
	}
	

	/**
	 * Sets the List's creation date.
	 * @parem timestamp $date
	 */
	private function setCreationDate($date){
		$this->creationDate = (int)$date;
	}

}

?>